package com.itheima.web;

import com.itheima.pojo.User;
import com.itheima.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        //获取浏览器传来的用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //获取用户输出的验证码
        String checkCode = request.getParameter("checkCode");


        //将数据封装成User对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        UserService service = new UserService();
        if (user.getUsername()==null || user.getUsername().length()==0||user.getPassword()==null||user.getPassword().length()==0){
            //提示用户用户名或者密码不能为空
            String Null_err="用户名或者密码不能为空";
            request.setAttribute("Null_err",Null_err);
            request.getRequestDispatcher("/register.jsp");
        }
        boolean register = service.register(user);
        //获取java生成的验证码
        HttpSession session = request.getSession();
        String  java_checkCode = (String )session.getAttribute("checkCode");
        System.out.println(java_checkCode);

        if (!java_checkCode.equalsIgnoreCase(checkCode)){
            //验证码输入不正确，给出错误提示信息,转发会注册页面
            String error_mag="验证码输入错误";
            request.setAttribute("checkCodeErr",error_mag);
            request.getRequestDispatcher("/register.jsp").forward(request,response);
            return;
        }
        if (register){
            //注册成功，转发道登录页面
            request.setAttribute("loginMSG","注册成功，请登录！");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }else{
            //注册失败，转发到注册页面，给出错误提示信息
            request.setAttribute("errorMSG","用户名已存在");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}